﻿using IKnow.Server.Data;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Yitter.IdGenerator;

namespace IKnow.Server.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ApiController : ControllerBase
    {
        private IFreeSql freeSql;
        public ApiController(IFreeSql fsql)
        {
            freeSql = fsql;
        }

        [HttpGet]
        public async Task<IActionResult> Get()
        {
            var query = await freeSql.Select<ApiEntity>()
                .IncludeMany(a => a.RequestParameters)
                .ToListAsync();

            return Ok(JsonConvert.SerializeObject(query));
        }


        [HttpPost]
        public async Task<IActionResult> Post(ApiEntity entity)
        {
            if (entity == null)
                throw new Exception("必要参数不能为空");
            if (entity.IsRequireParameter && (entity.RequestParameters == null || entity.RequestParameters.Count == 0))
                throw new Exception("必要参数不能为空");

            var result = 0;

            freeSql.Transaction(async () => //全局线程事务
            {
                entity.Id = YitIdHelper.NextId();
                result =await freeSql.Insert(entity).ExecuteAffrowsAsync();
                if (result < 1)
                    throw new Exception("操作失败");

                if (entity.IsRequireParameter && entity.RequestParameters != null && entity.RequestParameters.Count > 0)
                {
                    entity.RequestParameters.ForEach(a =>
                    {
                        a.Id = YitIdHelper.NextId();
                        a.ApiEntityId = entity.Id;
                    });
                    result = await freeSql.Insert(entity.RequestParameters).ExecuteAffrowsAsync();
                    if (result < 1)
                        throw new Exception("操作失败");
                }
            });

            return Ok(1);
        }
    }
}
